package com.douglas.managesystem.controller.admin;

import com.douglas.managesystem.common.ResponseResult;
import com.douglas.managesystem.common.RoleTypeEnum;
import com.douglas.managesystem.common.SearchEntity;
import com.douglas.managesystem.controller.BaseController;
import com.douglas.managesystem.entity.User;
import com.douglas.managesystem.entity.studentpojo.Student;
import com.douglas.managesystem.entity.studentpojo.Teacher;
import com.douglas.managesystem.service.admin.UserService;
import com.douglas.managesystem.service.student.StudentService;
import com.douglas.managesystem.service.student.TeacherService;
import com.douglas.managesystem.vo.UserPasswordVO;
import com.douglas.managesystem.vo.UserVO;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 用户管理
 * @Author 以梦为馬 <Douglas1314@126.com>
 * @Version V1.0.0
 * @Date 2020-10-26 15:48
 **/
@Controller
@RequestMapping("/admin")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    /**
     * 1.进入用户管理页面，分页查询用户
     */
    @GetMapping("/user/list")
    public String list(Model model, SearchEntity params) {
        PageInfo<User> page = userService.queryListByPage(params);
        model.addAttribute("user", page);
        return "admin/user/list";
    }

    /**
     * 2.去新增页面
     * @return
     */
    @GetMapping("/user/toAdd")
    public String toAdd(){
        return "admin/user/add";
    }

    /**
     * 3.新增/更新用户
     * @param user
     * @return
     */
    @PostMapping("/user/add")
    public String add(User user, HttpServletRequest request){
        if(StringUtils.isEmpty(user.getId())){
            try {
                String ip = request.getHeader("X-Forwarded-For");
                user.setLastLoginIp(ip);
                userService.addUser(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                userService.updateUser(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "redirect:/admin/user/list";
    }

    /**
     * 4.跳转编辑页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/user/toEdit")
    public String toEdit(Model model,String id){
        User user = userService.queryUserById(id);
        model.addAttribute("user",user);
        return "admin/user/edit";
    }

    /**
     * 5.删除用户
     * @param id
     * @return
     */
    @GetMapping("/user/delete")
    public String delete(String id){
        userService.deleteUser(id);
        return "redirect:/admin/user/list";
    }

    /**
     * 6.去更新密码页面
     * @return
     */
    @GetMapping("/user/toUpdatePwd")
    public ModelAndView toUpdatePwd(String id,String userRole){
        UserPasswordVO userPasswordVO = new UserPasswordVO();
        userPasswordVO.setId(id);
        userPasswordVO.setUserRole(userRole);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",userPasswordVO);
        mv.setViewName("admin/user/password");
        return mv;
    }


    /**
     * 7.更新密码
     * @param user
     * @return
     */
    @SuppressWarnings("all")
    @PostMapping("/user/updatePwd")
    @ResponseBody
    public ResponseResult updatePwd(@RequestBody UserPasswordVO user){
        UserVO loginUser = getLoginUser();
        // 0.创建返回对象
        ResponseResult responseResult = new ResponseResult();
    // 学生登录更新密码
        if(RoleTypeEnum.STUDENT.getCode().equals(user.getUserRole())){
            Student studentDb = studentService.findStuByStuNumber(user.getId());
            // 2.1 老 盐
            ByteSource oldSalt = ByteSource.Util.bytes(studentDb.getStuNumber() + user.getOldPwd());
            // 2.2 生成老密码
            SimpleHash oldPassword = new SimpleHash("MD5", user.getOldPwd(), oldSalt, 1024);
            // 3.判断数据库密码和输入的老密码是否一致
            if(!studentDb.getPassword().equals(oldPassword.toString())){
                responseResult.setSuccess(false);
                responseResult.setInfo("您输入的原密码错误！");
                return responseResult;
            }
            // 4.使用用户名和新的铭文密码生成新的密码
            // 4.1新盐
            ByteSource newSalt = ByteSource.Util.bytes(studentDb.getStuNumber() + user.getNewPwd());
            // 4.2新密码 加密
            SimpleHash newPassword = new SimpleHash("MD5", user.getNewPwd(), newSalt, 1024);
            studentDb.setPassword(newPassword.toHex());
            studentDb.setUpdatedBy(studentDb.getName());
            studentService.updateStudent(studentDb);
        }else if(RoleTypeEnum.TEACHER.getCode().equals(user.getUserRole())){
    // 老师更新密码
            Teacher teacher = teacherService.queryTeacherByTeacherId(user.getId());
            // 2.1 老 盐
            ByteSource oldSalt = ByteSource.Util.bytes(teacher.getTeacherId() + user.getOldPwd());
            // 2.2 生成老密码
            SimpleHash oldPassword = new SimpleHash("MD5", user.getOldPwd(), oldSalt, 1024);
            // 3.判断数据库密码和输入的老密码是否一致
            if(!teacher.getPassword().equals(oldPassword.toString())){
                responseResult.setSuccess(false);
                responseResult.setInfo("您输入的原密码错误！");
                return responseResult;
            }
            // 4.使用用户名和新的铭文密码生成新的密码
            // 4.1新盐
            ByteSource newSalt = ByteSource.Util.bytes(teacher.getTeacherId() + user.getNewPwd());
            // 4.2新密码 加密
            SimpleHash newPassword = new SimpleHash("MD5", user.getNewPwd(), newSalt, 1024);
            teacher.setPassword(newPassword.toHex());
            teacher.setUpdatedBy(teacher.getName());
            teacherService.editTeacher(teacher);
        }else {
    // 管理员与其他角色
            // 1.根据id查询用户
            User userDb = userService.queryUserById(user.getId());
            // 2.使用用户名和输入的铭文密码生成加密老密码
            // 2.1 老 盐
            ByteSource oldSalt = ByteSource.Util.bytes(userDb.getUsername() + user.getOldPwd());
            // 2.2 生成老密码
            SimpleHash oldPassword = new SimpleHash("MD5", user.getOldPwd(), oldSalt, 1024);
            // 3.判断数据库密码和输入的老密码是否一致
            if(!userDb.getPassword().equals(oldPassword.toString())){
                responseResult.setSuccess(false);
                responseResult.setInfo("您输入的原密码错误！");
                return responseResult;
            }
            // 4.使用用户名和新的铭文密码生成新的密码
            // 4.1新盐
            ByteSource newSalt = ByteSource.Util.bytes(userDb.getUsername() + user.getNewPwd());
            // 4.2新密码 加密
            SimpleHash newPassword = new SimpleHash("MD5", user.getNewPwd(), newSalt, 1024);
            userDb.setPassword(newPassword.toString());
            userDb.setUpdateBy(userDb.getUsername());
            userService.updatePassword(userDb);
        }
        responseResult.setSuccess(true);
        responseResult.setInfo("您的新密码更新成功，请重新登录！");
        return responseResult;
    }

    /**
     * 8.个人中心
     * @return
     */
    @GetMapping("/user/myCenter")
    public String toMyCenter(Model model){
        UserVO loginUser = getLoginUser();
        if(RoleTypeEnum.STUDENT.getCode().equals(loginUser.getUserRole().toString())){
            Student student = studentService.findStuByStuNumber(loginUser.getId());
            model.addAttribute("student",student);
            return "admin/myCenter/myCenterStu";
        }else if(RoleTypeEnum.TEACHER.getCode().equals(loginUser.getUserRole().toString())){
            Teacher teacher = teacherService.queryTeacherByTeacherId(loginUser.getId());
            model.addAttribute("teacher",teacher);
            return "admin/myCenter/myCenterTeach";
        }else{
            User user = userService.queryUserById(loginUser.getId());
            model.addAttribute("user",user);
            return  "admin/myCenter/myCenterAdmin";
        }
    }

}
